import sys

from woodblock_sprites import *



class PlaneGame(object):
    def __init__(self):
        """ 初始化方法 """
        # 1.创建游戏窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 设置窗口标题
        pygame.display.set_caption("电子木鱼 - 十八度天空")
        # 2.创建游戏时钟
        self.clock = pygame.time.Clock()
        # 3.初始化佛祖语录
        self.buddhist_phrases_dict = PlaneGame.__init__buddhist_phrases()
        # 4.创建精灵组
        self.__create_sprites()
        print(self.buddhist_phrases_dict)

    @staticmethod
    def __init__buddhist_phrases():
        # 判断文件是否存在
        if not os.path.exists("buddhist_phrases.json"):
            return {}
        # 1.从buddhist_phrases.json中获取json数据
        file = None
        try:
            file = open("buddhist_phrases.json", "r", encoding="utf-8")
            return json.load(file)
        except Exception as e:
            print(f"[错误] 初始化数据失败：{e}")
            return {}  # 出错也返回空字典
        finally:
            if file:
                file.close()

    def __create_sprites(self):
        """ 创建精灵组 """
        # 0.创建木鱼精灵
        self.woodblock = Woodblock()
        init_click_times = self.woodblock.click_times
        # 1.创建背景精灵
        bg = BackgroundSprite()
        self.background_group = pygame.sprite.Group(bg)
        # 2.创建文字精灵：电子木鱼
        text = TextSprite("电子木鱼", center=(SCREEN_RECT.centerx, 80))
        textDescStr = "菩提本无树，明镜亦非台。"
        textDesc = TextSprite(textDescStr, font_size=16,  color=(204, 204, 0), center = (200, 620))
        percent = min(int((init_click_times / 100000) * 100), 100)
        phrase = self.buddhist_phrases_dict.get(str(percent), "今日不谈钱，佛都有“元”人")
        self.mid_progress_text = TextSprite(phrase, font_size=16, color=(204, 204, 0), center=(140, 520))
        self.text_group = pygame.sprite.Group(text, textDesc, self.mid_progress_text)
        # 3.创建按钮精灵
        button = ButtonSprite(500, 600, 150, 50, "轻点敲击")
        self.button_group = pygame.sprite.Group(button)
        # 4.创建进度精灵组
        self.progress_bar = ProgressBarSprite(50, 550, 620, 30, max_value=100000, current_value=init_click_times)
        self.progress_group = pygame.sprite.Group(self.progress_bar)


    def __update_sprites(self):
        """ 更新精灵组 """
        # 填充背景色以清除上一帧内容
        self.screen.fill((0, 0, 0))
        # 更新背景精灵组
        self.background_group.update()
        self.background_group.draw(self.screen)
        # 更新文字精灵组
        self.text_group.update()
        self.text_group.draw(self.screen)
        # 更新按钮精灵组
        self.button_group.update()
        self.button_group.draw(self.screen)
        # 更新进度精灵组
        self.progress_group.update()
        self.progress_group.draw(self.screen)
        # 更新进度的文本精灵组
        self.progress_bar.progress_text_group.update()
        self.progress_bar.progress_text_group.draw(self.screen)

    def __event_handler(self):
        """ 事件监听 """
        for event in pygame.event.get():
            # 判断是否退出游戏
            if event.type == pygame.QUIT:
                self.game_over()
            # 处理鼠标事件，检测是否被点击
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()  # 获取当前鼠标位置 (x, y)
                button_rect = self.button_group.sprites()[0].rect  # 获取按钮的矩形区域
                # 判断鼠标是否点击在按钮上
                if button_rect.collidepoint(mouse_pos):
                    self.woodblock.click_times += 1
                    percent = int((self.woodblock.click_times / self.progress_bar.max_value) * 100)
                    percent = min(percent, 100)
                    # 更新进度条和百分比文本
                    formatted_percent = f"{(self.woodblock.click_times * 100 / self.progress_bar.max_value):.3f}%"
                    self.progress_bar.set_value(self.woodblock.click_times, formatted_percent)
                    # 更新进度条上面的文字
                    phrase = self.buddhist_phrases_dict.get(str(percent), "今日不谈钱，佛都有“元”人")
                    # 获取旧的 mid_progress_text 精灵
                    old_sprite = self.mid_progress_text
                    # 创建新的 mid_progress_text 精灵
                    new_sprite = TextSprite(phrase, font_size=16, color=(204, 204, 0), center=(140, 520))
                    # 替换引用
                    self.mid_progress_text = new_sprite
                    # 更新精灵组：先移除旧精灵，再添加新精灵
                    self.text_group.remove(old_sprite)
                    self.text_group.add(new_sprite)

    def start_game(self):
        """ 开始游戏 """
        while True:
            # 1.设置刷新帧率
            self.clock.tick(60)
            # 2.事件监听
            self.__event_handler()
            # 3.鼠标检测
            #self.__check_collide()
            # 4.更新/绘制精灵组
            self.__update_sprites()
            # 5.更新屏幕
            pygame.display.update()

    def game_over(self):
        """ 游戏结束 """
        self.woodblock.save_data()
        print("保存数据，游戏结束")
        pygame.quit()
        sys.exit()


if __name__ == '__main__':
    # 创建游戏对象
    game = PlaneGame()
    # 开始游戏
    game.start_game()